<script setup>
import { computed, inject, provide, ref, reactive, shallowReactive, onBeforeMount, onMounted, defineAsyncComponent } from 'vue'
import { DArrowRight, DArrowLeft, Avatar,House,Calendar,DataLine,UserFilled,Coordinate,Money,List,Plus} from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'

//核心功能页面
// import EmpListView from './emp/EmpListView.vue'
// import EmpAdd from './emp/EmpAdd.vue'
// import EmpSelf from './emp/EmpSelf.vue'
// import DeptListView from './dept/DeptListView.vue'
// import DeptAdd from './dept/DeptAdd.vue'
// import JobListView from './job/JobListView.vue'
// import JobAdd from './job/JobAdd.vue'
// import PerformanceListView from './performance/PerformanceListView.vue'
// import AttendanceListView from './attendance/AttendanceListView.vue'
// import SalaryListView from './salary/SalaryListView.vue'

//异步加载组件
const EmpListView = defineAsyncComponent(()=> import('./emp/EmpListView.vue'));
const EmpAdd = defineAsyncComponent(()=> import('./emp/EmpAdd.vue'));
const EmpSelf = defineAsyncComponent(()=> import('./emp/EmpSelf.vue'));
const DeptListView = defineAsyncComponent(()=> import('./dept/DeptListView.vue'));
const DeptAdd = defineAsyncComponent(()=> import('./dept/DeptAdd.vue'));
const JobListView = defineAsyncComponent(()=> import('./job/JobListView.vue'));
const JobAdd = defineAsyncComponent(()=> import('./job/JobAdd.vue'));
const PerformanceListView = defineAsyncComponent(()=> import('./performance/PerformanceListView.vue'));
const AttendanceListView = defineAsyncComponent(()=> import('./attendance/AttendanceListView.vue'));
const SalaryListView = defineAsyncComponent(()=> import('./salary/SalaryListView.vue'));

import NoMenuView from './NoMenuView.vue'

const appCurrentView = inject('appCurrentView');//app页面切换
function doLogOut() {//退出
    //TODO: 执行退出操作

    //成功后执行以下操作
    appCurrentView.name = 'Login';
    localStorage.removeItem('appCurrentView.name');
    localStorage.removeItem('mainCurrentView.name');
    localStorage.removeItem("login");
}

function dynamicImportComponent(dir, name) {//动态导入
    console.log('dynamicImportComponent begin==>');
    if(mainPageData[name]) {//存在则不再导入
        console.log('dynamicImportComponent 已导入');
        return;
    }
    import(/* @vite-ignore */ `${dir}/${name}.vue`).then((module)=>{
        mainPageData[name] = module.default;
        console.log('dynamicImportComponent 导入成功');
    }).catch((err)=>{
        ElMessage.error('页面加载失败，请稍候再试！');
        console.log('dynamicImportComponent 失败:', err);
    });
}

//Home中页面集合
const mainPageData = shallowReactive({
    'EmpListView': EmpListView,
    'EmpAdd': EmpAdd,
    'EmpSelf': EmpSelf,
    'DeptListView': DeptListView,
    'DeptAdd': DeptAdd,
    'JobListView': JobListView,
    'JobAdd': JobAdd,
    'PerformanceListView': PerformanceListView,
    'AttendanceListView': AttendanceListView,
    'SalaryListView': SalaryListView
});
//处理页面刷新
let mainCurrentViewName = localStorage.getItem('mainCurrentView.name');
console.log('mainCurrentViewName:', mainCurrentViewName);
if (mainCurrentViewName=='undefined' || mainCurrentViewName=='null' || !mainCurrentViewName) {
    mainCurrentViewName = 'EmpListView';//初次默认使用的页面
}
const mainCurrentView = reactive({name: mainCurrentViewName});

//检测页面切换
const mainCurrentComp = computed(()=>{
    if(isLoading.value) {//加载中
        return undefined;//不展示主界面
    }
    let index = mainCurrentView.name;
    //console.log('index:', index, ', menuIndexArr.includes:', menuIndexArr.value.includes(index), ', menuIndexArr:', menuIndexArr.value);
    if(!menuIndexArr.value.includes(index)) {//默认展示页面index不在菜单index中
        if(menuIndexArr.value.length == 0) {//无菜单
            return NoMenuView;//无菜单权限展示页面
        }
        index = menuIndexArr.value[0];//默认展示第一个菜单
        defaultActiveIndex.value = index;
    }
    const comp = mainPageData[index];//获取对应页面组件
    //存储当前页面index
    localStorage.setItem('mainCurrentView.name', mainCurrentView.name);
    return comp;
});
//提供main页面切换操作
provide('mainCurrentView', mainCurrentView);

//左侧导航菜单
const defaultActiveIndex = ref(mainCurrentViewName);
const isCollapse = ref(false);
function doMainMenuSelect(key, keyPath) {//切换菜单
    console.log('doMainSelect:', key, keyPath);
    mainCurrentView.name = key;
    defaultActiveIndex.value = key;
}

//菜单数据
const menuArr = ref([]);
const menuIndexArr = ref([]);//可用菜单的index,用于主页显示校验
// 可用菜单: 部门 职位 员工信息 工资发放 绩效考核 考勤记录
const empSelfMenu = shallowReactive({index: 'EmpSelf', name:'个人中心', children:[], icon: Avatar});
const deptMenu = shallowReactive({index: 'dept', name:'部门管理', children:[
    {index: 'DeptListView', name:'部门列表', icon: List},
    {index: 'DeptAdd', name:'部门添加', icon: Plus}
], icon: House});
const jobMenu = shallowReactive({index: 'job', name:'职位管理', children:[
    {index: 'JobListView', name:'职位列表', icon: List},
    {index: 'JobAdd', name:'职位添加', icon: Plus}
], icon: Coordinate});
const empMenu = shallowReactive({index: 'emp', name:'员工管理', children:[
    {index: 'EmpListView', name:'员工列表', icon: List},
    {index: 'EmpAdd', name:'员工添加', icon: Plus}
], icon: UserFilled});
const salaryMenu = shallowReactive({index: 'SalaryListView', name:'工资发放', children:[], icon: Money});
const performanceMenu = shallowReactive({index: 'PerformanceListView', name:'绩效考核', children:[], icon: DataLine});
const attendanceMenu = shallowReactive({index: 'AttendanceListView', name:'考勤记录', children:[], icon: Calendar});

const isLoading = ref(true);
function doMenuLoading() {
    menuArr.value = [];//菜单
    menuIndexArr.value = [];//菜单index
    isLoading.value = true;
    //获取用户的菜单权限 1 表示普通员工, 2 管理员员工
    //普通员工, 只能操作自己的; 管理员员工 操作所有数据
    let powerKey = loginUser.value.powerKey;//1 表示普通员工, 2 管理员员工
    setTimeout(()=>{//模拟数据处理结束
        //菜单权限处理
        if(powerKey == 1) {
            menuArr.value.push(empSelfMenu);
            doAddMenuIndex(empSelfMenu);

            menuArr.value.push(salaryMenu);
            doAddMenuIndex(salaryMenu);

            menuArr.value.push(performanceMenu);
            doAddMenuIndex(performanceMenu);
            
            menuArr.value.push(attendanceMenu);
            doAddMenuIndex(attendanceMenu);

        } else if (powerKey == 2) {
            menuArr.value.push(empSelfMenu);
            doAddMenuIndex(empSelfMenu);

            menuArr.value.push(deptMenu);
            doAddMenuIndex(deptMenu);

            menuArr.value.push(jobMenu);
            doAddMenuIndex(jobMenu);

            menuArr.value.push(empMenu);
            doAddMenuIndex(empMenu);

            menuArr.value.push(salaryMenu);
            doAddMenuIndex(salaryMenu);

            menuArr.value.push(performanceMenu);
            doAddMenuIndex(performanceMenu);
            
            menuArr.value.push(attendanceMenu);
            doAddMenuIndex(attendanceMenu);
        }

        isLoading.value = false;
    }, 1000);
}
function doAddMenuIndex(menu) {
    if(menu.children && menu.children.length > 0) {
        //有子菜单
        menu.children.forEach(ele => {
            menuIndexArr.value.push(ele.index);
        });
    } else {
        //无子菜单
        menuIndexArr.value.push(menu.index);
    }
}

function addMenu() {//测试动态菜单(暂未使用)
    let i = menuArr.value.length+1;
    menuArr.value.push(shallowReactive({index: i+'', name:'菜单'+i, children:[
        shallowReactive({index: i+'1', name:'菜单'+i+'-1', children:[], icon: House}),
        shallowReactive({index: i+'2', name:'菜单'+i+'-2', children:[], icon: House}),
    ], icon: House}));
    //console.log(menuArr.value);
    //menuArr.value[0].name = 'aaaa';
}

// 登录关联,校验用户是否登录等
const loginUser = ref({});//登录的用户,示例 {loginName:'tom', name:'汤姆', powerKey: 1, token: 't123'}
const isLogin = ref(false);
function getLoginUser() {//获取本地存储的用户信息
    let str = localStorage.getItem("login");
    if(str) {
        loginUser.value = JSON.parse(str);
    }
    if(!loginUser.value || !loginUser.value.token) {
        ElMessage.warning('您还未登录，请先登录');
        setTimeout(()=>{
            doLogOut();
        }, 1000);
        return;
    }
    isLogin.value = true;
}
function showSelfView() {//点击右上角 用户名 的操作
    mainCurrentView.name = 'EmpSelf';
    defaultActiveIndex.value = 'EmpSelf';
}

// 挂载前进行登录校验
onBeforeMount(()=>{
    getLoginUser();
    if(isLogin.value) {
        doMenuLoading();
    } else {
        isLoading.value = false;
    }
});
</script>
<template>
    <div class="home-container" v-if="isLogin" v-loading="isLoading">
        <el-container>
            <el-aside class="aside-dl">

                <el-menu class="menu-dl"
                :default-active="defaultActiveIndex" mode="vertical"
                @select="doMainMenuSelect" :collapse="isCollapse"
                >
                    <div @click="isCollapse=!isCollapse" class="setting-dl">
                        <el-icon color="white" size="20">
                            <DArrowRight v-if="isCollapse" />
                            <DArrowLeft v-else />
                        </el-icon>
                    </div>
                    <template v-for="m in menuArr" :key="m.index" >
                        <el-sub-menu v-if="m.children.length > 0" :index="m.index">
                            <template #title>
                                <el-icon><component :is="m.icon" /></el-icon>
                                <span>{{m.name}}</span>
                            </template>
                            <el-menu-item v-for="cm in m.children" :key="cm.index" :index="cm.index">
                                <el-icon><component :is="cm.icon" /></el-icon>
                                <span>{{cm.name}}</span>
                            </el-menu-item>
                        </el-sub-menu>
                        <el-menu-item v-else :index="m.index">
                            <el-icon><component :is="m.icon" /></el-icon>
                            <span>{{m.name}}</span>
                        </el-menu-item>
                    </template>
                </el-menu>

            </el-aside>
            <el-container class="right-container-dl" >
                <el-header height="60px" class="header-dl" >
                    <el-link class="title-dl" type="primary" :underline="false">人力资源管理系统</el-link>
                    <div class="header-user">
                        <el-text class="mx-1" type="primary">欢迎：</el-text>
                        <el-link style="line-height: normal;" @click="showSelfView">{{loginUser.name}}</el-link>
                        <el-link class="header-logout-dl" type="warning" @click="doLogOut">注销</el-link>
                    </div>
                </el-header>
                <el-main>
                    <component :is="mainCurrentComp"/>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>
<style scoped>
.home-container {
    padding: 10px;
}
.home-container .aside-dl {
    width: auto;
}
.home-container .setting-dl {
    cursor: pointer;
    padding-top: 10px;
    text-align: center;
}
.right-container-dl {
    min-height: 98vh;
}
.menu-dl {
    height: 100%;
    /* menu已被废弃属性 background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" */
    /* 以下是替代 */
    --el-menu-text-color: #fff;
    --el-menu-hover-text-color: #fff;
    --el-menu-bg-color: #545c64;
    --el-menu-hover-bg-color: #434a50;
    --el-menu-active-color: #ffd04b;
}
.header-dl {
    border-bottom: 1px solid #ccc;
    line-height: 60px;
}
.header-dl .title-dl {
    font-size: 30px;
}
.header-dl .header-user {
    float: right;
}
.header-dl .header-logout-dl {
    margin-left: 10px;
    line-height: normal;
}
</style>